﻿using UnityEngine;
using System.Collections;
using UnityExtensions;

/// <summary>
/// unity MonoBehaviour单例模板
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>, new()
{
	protected static T s_Instance = null;
	/// <summary>
	/// 检测实例是否为null的标志
	/// 用于解决unity new Object() == null 为true的情况
	/// </summary>
	protected static bool instanceIsNull = true;
	/// <summary>
	/// 取得当前对象的一个单例
	/// </summary>
	public static T instance
	{
		get
		{
			if (instanceIsNull)
			{
				var ins = FindObjectOfType<T>();
				if (!ins)
				{
					var mainObj = GameObjectUtility.FindOrNew("Main");
					DontDestroyOnLoad(mainObj);
					ins = mainObj.AddComponent<T>();
				}
				ins.AppyInstance();
			}
			return s_Instance;
		}
	}
	protected virtual void Awake()
	{
		AppyInstance();
	}
	protected virtual void Start()
	{

	}
	protected void AppyInstance()
	{
		if (instanceIsNull)
		{
			s_Instance = this as T;
			instanceIsNull = false;
		}
	}
}

public class SingletonTransform
{
	private static Transform mMainTransform;                      //

	public static Transform MainTransform	
	{
		get
		{
			if (mMainTransform == null)
			{
				mMainTransform = GameObjectUtility.FindOrNew("Main").transform;
			}

			return mMainTransform;
		}
	}

	private static Transform mPoolTransf; //

	public static Transform PoolTransf
	{
		get
		{
			if (mPoolTransf == null)
			{
				mPoolTransf = MainTransform.FindOrNew("PoolRoot");
			}

			return mPoolTransf;
		}
	}

}

public class SingletonUObject<T> where T : UnityEngine.Object, new()
{

}
/// <summary>
/// C#单例模板
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonObject<T> where T : class, new()
{
	protected static T m_this = null;
	//取得当前对象的一个单例
	public static T GetInstance()
	{
		return m_this ?? (m_this = new T());
	}
}
